package cn.calm.osgi.conter;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * ServletContextListener that starts Apache Felix
 */
public class OsgiListener implements ServletContextListener {
    public static final String OSGI_HOST = "__osgi_host";
    private FelixOsgiHost osgiHost;
    public static final String SERVICE_HTTP_PORT="serviceHttpPort";
    public void contextInitialized(ServletContextEvent sce) {
//    	
    	ServletContext servletContext = sce.getServletContext();
    	System.setProperty("org.osgi.service.http.port", servletContext.getInitParameter(SERVICE_HTTP_PORT));
        osgiHost = new FelixOsgiHost();
//        servletContext.getInitParameter("");
        servletContext.setAttribute(OSGI_HOST, osgiHost);
        try {
            osgiHost.init(servletContext);
        } catch (Exception e) {
            throw new RuntimeException("Apache Felix failed to start", e);
        }
        Runnable run=new Runnable() {
			
			@Override
			public void run() {
				try {
					ServerSocket serverSocket=new ServerSocket(10000);
					while(true){
						Socket accept = serverSocket.accept();
						System.out.println(accept);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(run).start();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        try {
            osgiHost.destroy();
        } catch (Exception e) {
            throw new RuntimeException("Apache Felix failed to stop", e);
        }
    }
}
